package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.assembler.ScannerConsigneeAssembler;
import com.wlyuan.open.scanner.config.GroupProperties;
import com.wlyuan.open.scanner.constant.AddressTypeEnum;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.dao.entity.EndUserDO;
import com.wlyuan.open.scanner.dao.mapper.CustomerMapper;
import com.wlyuan.open.scanner.dao.mapper.EndUserMapper;
import com.wlyuan.open.scanner.domain.consignee.Consignee;
import com.wlyuan.open.scanner.domain.consignee.ConsigneeConvert;
import com.wlyuan.open.scanner.repository.AddressRepository;
import com.wlyuan.open.scanner.repository.ConsigneeRepository;
import com.wlyuan.open.scanner.utils.enums.YesOrNoEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ConsigneeRepositoryImpl implements ConsigneeRepository {
    private final EndUserMapper endUserMapper;
    private final CustomerMapper customerMapper;
    private final AddressRepository addressRepository;
    private final BaseOrderRepository baseOrderRepository;
    private final GroupProperties groupProperties;

    @Override
    public void sync() {
        logger.info("收货方所属公司ID大于0");
        int count = endUserMapper.count();
        logger.info("收货方老数据数据量，size：{}", count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        for (int i = 1; i <= pages; i++) {
            logger.info("开始同步收货方：第{}页，共{}页", i, pages);
            var list = endUserMapper.getConsigneeIds(i, Constants.PAGE_SIZE);
            list.forEach(id -> {
                try {
                    var data = endUserMapper.getById(id);
                    process(data);
                    baseOrderRepository.sync(ScannerConsigneeAssembler.assemble(ConsigneeConvert.convert(data)));
                } catch (Exception e) {
                    logger.error("收货方同步异常：{}，{}", id, e);
                }
            });
        }
        logger.info("收货方同步完成......");
    }

    @Override
    public List<Consignee> list() {
        return Collections.emptyList();
    }

    @Override
    public Consignee getById(Long consigneeId) {
        return Optional.ofNullable(consigneeId).map(id -> {
            var data = endUserMapper.getById(id);

            return Optional.ofNullable(data).map(consignee -> {
                process(consignee);
                return ConsigneeConvert.convert(consignee);
            }).orElse(null);

        }).orElse(null);

    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return endUserMapper.getByTime(startTime, endTime);
    }

    @Override
    public List<Long> getByTenantIdTime(Long tenantId, String startTime, String endTime) {
        return endUserMapper.getByTenantIdTime(tenantId, startTime, endTime);
    }

    @Override
    public void getByTenantId(Long tenantId) {
        logger.info("收货方所属公司ID大于0");
        int count = endUserMapper.countByTenantId(tenantId);
        logger.info("租户{}收货方老数据数据量，size：{}", tenantId, count);
        var pages = (int) Math.ceil(count * 1.0 / Constants.PAGE_SIZE);
        for (int i = 1; i <= pages; i++) {
            logger.info("开始同步租户{}收货方：第{}页，共{}页", tenantId, i, pages);
            var list = endUserMapper.getConsigneeIdsByTenantId(i, Constants.PAGE_SIZE, tenantId);
            list.forEach(id -> {
                try {
                    var data = endUserMapper.getById(id);
                    process(data);
                    baseOrderRepository.sync(ScannerConsigneeAssembler.assemble(ConsigneeConvert.convert(data)));
                } catch (Exception e) {
                    logger.error("收货方同步异常：{}，{}", id, e);
                }
            });
        }
        logger.info("租户{}收货方同步完成......", tenantId);
    }

    @Override
    public void process(EndUserDO data) {
        var addressMap = addressRepository.getAddress(data.getEnduserId(), AddressTypeEnum.RECEIVINGADDRESS.getValue());
        data.setAddressList(addressMap.get(data.getEnduserId()));
        if (StringUtils.isBlank(data.getEnduserContact())) {
            data.setEnduserContact(data.getEnduserName());
        }
        if (StringUtils.isBlank(data.getEnduserPhone())) {
            data.setEnduserPhone(Constants.CONSIGNEE_CONTRACT_MOBILE);
        }
        if (data.getEnduserSituponestatus() != null && YesOrNoEnum.isYes(data.getEnduserSituponestatus())) {
            data.setDeliveryTime(new ArrayList<>(Arrays.asList(6, 0)));
        }
        if (StringUtils.isNotBlank(data.getEnduserSetstatus()) && YesOrNoEnum.isYes(data.getEnduserPostponestatus())) {
            setDeliverTime(data);
        }
        if (groupProperties.groupTenantList().contains(data.getEnduserOwnercompany())) {
            data.setEnduserUpdater(0L);
            data.setEnduserCreator(0L);
            data.setCustomerName(Constants.GROUP_MAP.get(data.getEnduserOwnercompany()));
            //ownerCompanyId = companyId 自己 或 类型为线下时，才转换客户名称
            //老系统客户名称与新系统试用数据名称不一致 如：脱普日用化学品（中国）有限公司 --> 脱普日用化学品
            var customer = customerMapper.getById(data.getEnduserCustomerid());
            if (!Optional.ofNullable(customer).isPresent()) {
                data.setCustomerName(Constants.GROUP_MAP.get(data.getEnduserOwnercompany()));
            } else if (customer.getCustomerOwnercompany().equals(customer.getCustomerCompanyid()) || customer.getCustomerUnderline() == 0) {
                data.setCustomerName(Constants.GROUP_MAP.get(data.getEnduserOwnercompany()));
            }
        }
    }


    private static void setDeliverTime(EndUserDO endUser) {
        try {
            List<Integer> deliveryTime = Optional.ofNullable(endUser.getDeliveryTime()).orElseGet(() -> new ArrayList<>());
            //判断文本是否包含;
            if (endUser.getEnduserSetstatus().contains(";")) {
                String[] split = endUser.getEnduserSetstatus().split(";");
                if (split[0].contains("、")) {
                    //切分周六日
                    String[] satSum = split[0].split("、");
                    deliveryTime.add(Integer.valueOf(satSum[0]));
                    deliveryTime.add(Integer.valueOf(satSum[1]));
                } else {
                    deliveryTime.add(Integer.valueOf(split[0]));
                }
                if (split[1].contains("、")) {
                    String[] holiday = split[1].split("、");
                    deliveryTime.add(Integer.valueOf(holiday[0]));
                    deliveryTime.add(Integer.valueOf(holiday[1]));
                } else {
                    deliveryTime.add(Integer.valueOf(split[1]));
                }
            } else if (endUser.getEnduserSetstatus().contains("、")) {
                String[] split = endUser.getEnduserSetstatus().split("、");
                deliveryTime.add(Integer.valueOf(split[0]));
                deliveryTime.add(Integer.valueOf(split[1]));
            } else {
                deliveryTime.add(Integer.valueOf(endUser.getEnduserSetstatus()));
            }
            endUser.setDeliveryTime(deliveryTime.stream().distinct().collect(Collectors.toList()));
        } catch (Exception e) {
            logger.error("收货方DeliverTime，收货方id：{},{}", endUser.getEnduserId(), endUser.getEnduserSetstatus());
            e.printStackTrace();
        }
    }
}
